//
//  SFPlayerResourceLoader.m
//  Test
//
//  Created by xueshan1 on 2018/11/14.
//  Copyright © 2018年 xueshan1. All rights reserved.
//

#import "SFPlayerResourceLoader.h"
#import "SFPlayerRequestManager.h"
#import <MobileCoreServices/MobileCoreServices.h>

#define MimeType @"video/mp3"

@interface SFPlayerResourceLoader ()<SFPlayerRequestDelegate>

@property(nonatomic,strong)NSMutableArray *requestList;
@property(nonatomic,strong)SFPlayerRequestManager *requestManager;

@end

@implementation SFPlayerResourceLoader
- (instancetype)init
{
    self = [super init];
    if (self) {
        _requestList = [NSMutableArray array];
    }
    return self;
}

#pragma mark - AVAssetResourceLoaderDelegarte
//要求加载资源
- (BOOL)resourceLoader:(AVAssetResourceLoader *)resourceLoader shouldWaitForLoadingOfRequestedResource:(AVAssetResourceLoadingRequest *)loadingRequest{
    
    [self addLoadingRequest:loadingRequest];
    
    return YES;
}
//取消加载
- (void)resourceLoader:(AVAssetResourceLoader *)resourceLoader didCancelLoadingRequest:(AVAssetResourceLoadingRequest *)loadingRequest{
    
    [self.requestList removeObject:loadingRequest];
}
- (void)addLoadingRequest:(AVAssetResourceLoadingRequest *)loadingRequest{
    [self.requestList addObject:loadingRequest];
    
    if (self.requestManager) {
        if (loadingRequest.dataRequest.requestedOffset >= self.requestManager.requestOffset &&
            loadingRequest.dataRequest.requestedOffset <= self.requestManager.requestOffset + self.requestManager.cacheLength) {
            //seek后的位置,已经被加载了
            [self processRequestList];
        }else{
            //从seek后的位置开始加载
            if (self.isSeek) {
//                [self newTaskWithLoadingRequest:loadingRequest cache:NO];
            }
        }
        
    }else{
        [self newTaskWithLoadingRequest:loadingRequest cache:YES];
    }
    
}
//请求
- (void)newTaskWithLoadingRequest:(AVAssetResourceLoadingRequest *)loadingRequest cache:(BOOL)cache{
    NSUInteger fileLength = 0;
    if (self.requestManager) {
        //被seek,记录文件的长度,然后取消现在的请求,
        fileLength = self.requestManager.fileLength;
        self.requestManager.cancel = YES;
    }
    
    self.requestManager = [[SFPlayerRequestManager alloc]initWithRequestUrl:loadingRequest.request.URL.absoluteString];
    self.requestManager.requestOffset = loadingRequest.dataRequest.requestedOffset; //开始请求的位置
    self.requestManager.cache = cache;
    if (fileLength > 0) {
        self.requestManager.fileLength = fileLength;
    }
    
    self.requestManager.delegate = self;
    [self.requestManager startRequest];
    self.isSeek = NO;
}

#pragma mark - RequestDelegate
- (void)sessionRequestDidReceiveData:(NSData *)data{
    //接收数据->填充->响应
    [self processRequestList];
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(resourceLoader:cacheProgress:)]) {
        CGFloat cacheProgress = (CGFloat)self.requestManager.cacheLength/(self.requestManager.fileLength - self.requestManager.requestOffset);
        [self.delegate resourceLoader:self cacheProgress:cacheProgress];
    }
}
- (void)sessionRequestDidFinishLoadingWithCache:(BOOL)cache{
    self.cacheFinished = cache;
    
}
//处理loadingRequest, 填充响应数据
- (void)processRequestList{
    NSMutableArray *finishRequestList = [NSMutableArray array];
    for (AVAssetResourceLoadingRequest *loadingRequest in self.requestList) {
        if ([self finishLoadingWithLoadingRequest:loadingRequest]) {
            [finishRequestList addObject:loadingRequest];
        }
    }
    [self.requestList removeObjectsInArray:finishRequestList];
}

//填充 contentInformationRequest
- (BOOL)finishLoadingWithLoadingRequest:(AVAssetResourceLoadingRequest *)loadingRequest{
    //填充信息
    CFStringRef contentType = UTTypeCreatePreferredIdentifierForTag(kUTTagClassMIMEType, (__bridge CFStringRef)(MimeType), NULL);
    loadingRequest.contentInformationRequest.contentType = CFBridgingRelease(contentType);
    loadingRequest.contentInformationRequest.byteRangeAccessSupported = YES;
    loadingRequest.contentInformationRequest.contentLength = self.requestManager.fileLength;
    
    //填充数据
    NSUInteger cacheLength = self.requestManager.cacheLength;
    NSUInteger requestOffset = loadingRequest.dataRequest.requestedOffset;
    if (loadingRequest.dataRequest.currentOffset != 0) {
        requestOffset = loadingRequest.dataRequest.currentOffset;
    }
    
//    NSUInteger canReadLength = cacheLength - (requestOffset - self.requestManager.requestOffset);
//    NSUInteger responseLength = MIN(canReadLength, loadingRequest.dataRequest.requestedLength);
//    [loadingRequest.dataRequest respondWithData:[SFFileHandle readTempFileDataWithOffset:requestOffset - self.requestManager.requestOffset length:responseLength]];
    NSUInteger canReadLength = cacheLength - requestOffset;
    NSUInteger responseLength = MIN(canReadLength, loadingRequest.dataRequest.requestedLength);
    [loadingRequest.dataRequest respondWithData:[SFFileHandle readTempFileDataWithOffset:requestOffset length:responseLength]];
    
    //完成
    //响应数据结束的位置 >= loadingRequest结束的位置
    NSUInteger nowEndOffset = requestOffset + canReadLength;
    NSUInteger reqEndOffset = loadingRequest.dataRequest.requestedOffset + loadingRequest.dataRequest.requestedLength;
    if (nowEndOffset >= reqEndOffset) {
        [loadingRequest finishLoading];
        return YES;
    }
     
    return NO;
}

- (void)stopLoadding{
    self.requestManager.cancel = YES;
    
}


@end
